<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <van-cell-group>
      <van-field
        v-model.trim="form.mobile"
        :error-message="error.mobile"
        @blur="validateMobile"
        label="手机号"
        type="tel"
        placeholder="请输入手机号"
      />
      <van-field
        v-model.trim="form.code"
        :error-message="error.code"
        @blur="validateCode"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
      >
        <template slot="button">
          <van-button size="small">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-box">
      <van-button @click="login" round block type="info">提交</van-button>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'user-chat',
  data () {
    return {
      form: {
        // mobile: '13911111111',
        mobile: '15801018888',
        code: '246810'
      },
      error: {
        mobile: '',
        code: ''
      }
    }
  },
  created () {
    console.log(this.$route, this.$router, this.$toast)
  },
  methods: {
    ...mapMutations(['setToken']),
    // 校验手机
    validateMobile () {
      const { mobile } = this.form
      if (!mobile) {
        this.error.mobile = '手机号不能为空！'
      } else if (!/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(mobile)) {
        this.error.mobile = '手机号格式不正确！'
      } else {
        this.error.mobile = ''
      }
    },
    // 校验验证码
    validateCode () {
      const { code } = this.form
      if (!code) {
        this.error.code = '验证码不能为空！'
      } else if (!/^\d{6}$/.test(code)) {
        this.error.code = '验证码为6位数字'
      } else {
        this.error.code = ''
      }
    },
    async login (e) {
      this.validateMobile()
      this.validateCode()
      if (this.error.mobile || this.error.code) return
      // 登录
      // console.log(e)
      // try {
      //   await Promise.reject(new Error('错误！'))
      // } catch (error) {
      //   console.log(error)
      // }
      try {
        const { data } = await login(this.form)
        // console.log(data)
        this.$toast.success('登录成功！')
        this.setToken(data)
        this.$router.replace(this.$route.query.redirectUrl || '/user')
      } catch (error) {
        // 捕获promise异常
        // console.log(error)
        this.$toast.fail('手机号或验证码错误！')
      }
    }
  }
}
</script>

<style scoped lang='less'>
.btn-box {
  margin: 10px;
  .van-button {
    height: 35px;
  }
}
</style>
